﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Travasto.Model;

namespace Travasto.Web.Areas.Admin.Commands
{
    public class AddTagsCommand
    {
        public ICollection<Tag> Tags { get; set; }
        public TravastoDbContext DbContext { get; set; }

        public AddTagsCommand(ICollection<Tag> tags,TravastoDbContext context)
        {
            this.Tags = tags;
            this.DbContext = context;
        }

        public ICollection<Tag> Execute() {
            if (Tags == null)
                return null;
            if (Tags.Count == 0)
                return Tags;

            var allTags = Tags.Select(ta => ta.Name);

            // retrieve existing tags
            var existedTags = DbContext.Tags.Where(t => allTags.Contains(t.Name)).ToList();
            
            // filter out new tags
            var newTags = Tags.Where(t => !existedTags.Select(ta => ta.Name).Contains(t.Name)).ToList();

            // save new tags to database
            if (newTags.Count > 0)
            {
                newTags.ForEach(t => { DbContext.Tags.Add(t); });
                DbContext.SaveChanges();
            }
            
            // retrieve all the tags
            existedTags = DbContext.Tags.Where(t => allTags.Contains(t.Name)).ToList();

            return existedTags;
        }
    }
}